/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.mall.shopping.web.PaymentInfoAction
   Module Description   :

   Date Created      : 2010/1/18
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.mall.shopping.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.geronimo.mail.util.Base64;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONUtil;
import org.apache.velocity.tools.generic.DateTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.campaign.entity.CampaignProduct;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.channel.entity.ChannelTemplate;
import com.yaodian100.ec.channel.service.ChannelService;
import com.yaodian100.ec.cobranding.Onlylady;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.coupon.service.CouponService;
import com.yaodian100.ec.creditcard.entity.Creditcard;
import com.yaodian100.ec.creditcard.entity.CreditcardDetail;
import com.yaodian100.ec.creditcard.service.CreditcardService;
import com.yaodian100.ec.givebonus.entity.BonusSetting;
import com.yaodian100.ec.member.entity.Balance;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.payment.service.TransferService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;
import com.yaodian100.mall.member.util.UserData;

/**
 * @author ellen.li
 * 
 */
public class PaymentInfoAction extends ActionSupport implements Preparable {

	/**
	 * 訂購完成
	 */
	private static final long serialVersionUID = -7708767341562431466L;
	private final Logger logger = LoggerFactory.getLogger(PaymentInfoAction.class);
	private CartOrdersService cartordersService;
	private MemberService memberService;
	private OrderService orderService;
	private CouponService couponService;
	private TransferService transferService;
	private ChannelService channelService;
	private LogService logService;
	private final CommonCriteria crit = new CommonCriteria();
	private List<CartOrderProductDetail> cartOrderProductDetailList;
	private List<CartOrderProduct> cartOrderProductList;
	private Member member;
	private Orders orders;
	private OrderProduct orderProduct;
	private OrderProductDetail orderProductDetail;
	private List<OrderProductDetail> orderProductDetailList;
	private List<OrderProduct> orderProductList;
	private List<Orders> joinOrderList;
	private ProductService productService;
	private CategoryService categoryService;
	private TemplateService velocityService;
	@Autowired
	private TimeLimitSaleService timeLimitSaleService;
	@Autowired
	private CartOrdersService cartOrderService;
	@Autowired
	private CreditcardService creditcardService;
	// 前端頁面參數
	private String paytype;// 付款方式
	private String contactName;// 收货人姓名
	private String province = " ";// 省份
	private String city = " ";// 市
	private String district = " ";// 区
	private String zipCode;// 邮编
	private String addr;// 街道
	private String areaCode;
	private String phone;
	private String extension;
	private String mobile;
	private String memo;
	private Menu paymentTpMenu; // 與 getter, setter
	private Menu productTpMenu;
	private Menu rateMenu;
	private Menu bankCodeMenu;
	private Menu paymentSrcMenu;
	private DomainService<Menu> menuService; // 與 setter
	private String orderId;
	private String chkVrtBlnc;
	private String chkGiftCard;
	private String chkCoupon;
	private String chkBonus;
	private String couponInfo;
	private String editBonus;
	private String editCoupon;
	private String addCmpPd;
	private String editShipFare = "";
	private String[] buyNowInfo;// 直接購買
	private int productCount;
	private Product product;
	private String channelFlag = "N";
	private String orderInfoView = "/shopping/paymentInfo/paymentInfoView.do?orderId=";
	private String adwaysInfo;

	private String campaigns;

	private String buyNowCartId;
	private String addCmpPdId;

	private String finalTotalAmount;
	private String editTotalAmount;
	private String cartMessage;
	private String channelResult;
	private String gwdScript;
	private String storeId;
	private String bitem;
	private String b100item = "";
	private String mail;
	private String reqMap;
	private String rsPage;
	private String canUse;
	private String ccode;
	private String creditcardDetailId;
	private String editPeriod;
	private Creditcard creditcard;// 信用卡分期
	private CreditcardDetail creditcardDetail;
	private String editPeriodAmount;// 分期手续费
	private String allowSplit;// 付款方式

	private BonusSetting bonusSetting;
	@Resource
	private AddessService addressService;

	private String orderMemoAlert;

	private Menu billBankCodeMenu; // 快钱menu code
	private Menu billBankSingleCodeMenu; // 快钱menu code單期支付
	private Map<String, String> prodVolumeMap;// 大材积商品
	// 发票信息
	private String invotype;// 01－个人，02－单位
	private String invoTitle;
	@Autowired
	private MailService mailService;
	private Menu systemValueMenu;// 系统参数

	/**
	 * @return the editTotalAmount
	 */
	public String getEditTotalAmount() {
		return editTotalAmount;
	}

	/**
	 * @param editTotalAmount the editTotalAmount to set
	 */
	public void setEditTotalAmount(String editTotalAmount) {
		this.editTotalAmount = editTotalAmount;
	}

	@Resource
	private BaseManager baseMgr;

	public String getAddCmpPd() {
		return addCmpPd;
	}

	/**
	 * @return the addCmpPdId
	 */
	public String getAddCmpPdId() {
		return addCmpPdId;
	}

	public String getAddr() {
		return addr;
	}

	public String getAdwaysInfo() {
		return adwaysInfo;
	}

	public String getAreaCode() {
		return areaCode;
	}

	/**
	 * @return the buyNowCartId
	 */
	public String getBuyNowCartId() {
		return buyNowCartId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	public String[] getBuyNowInfo() {
		return buyNowInfo;
	}

	/**
	 * @return the campaigns
	 */
	public String getCampaigns() {
		return campaigns;
	}

	/**
	 * @return the cartMessage
	 */
	public String getCartMessage() {
		return cartMessage;
	}

	public List<CartOrderProductDetail> getCartOrderProductDetailList() {
		return cartOrderProductDetailList;
	}

	public List<CartOrderProduct> getCartOrderProductList() {
		return cartOrderProductList;
	}

	public CartOrdersService getCartordersService() {
		return cartordersService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public String getChannelFlag() {
		return channelFlag;
	}

	public String getChannelResult() {
		return channelResult;
	}

	public ChannelService getChannelService() {
		return channelService;
	}

	public String getChkVrtBlnc() {
		return chkVrtBlnc;
	}

	public String getCity() {
		return city;
	}

	public String getContactName() {
		return contactName;
	}

	public String getCouponInfo() {
		return couponInfo;
	}

	public CouponService getCouponService() {
		return couponService;
	}

	public String getDistrict() {
		return district;
	}

	public String getEditBonus() {
		return editBonus;
	}

	public String getEditShipFare() {
		return editShipFare;
	}

	public String getExtension() {
		return extension;
	}

	/**
	 * @return the finalTotalAmount
	 */
	public String getFinalTotalAmount() {
		return finalTotalAmount;
	}

	public Member getMember() {
		return member;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public String getMemo() {
		return memo;
	}

	public String getMobile() {
		return mobile;
	}

	public String getOrderId() {
		return orderId;
	}

	public String getOrderInfoView() {
		return orderInfoView;
	}

	public OrderProduct getOrderProduct() {
		return orderProduct;
	}

	public OrderProductDetail getOrderProductDetail() {
		return orderProductDetail;
	}

	public List<OrderProductDetail> getOrderProductDetailList() {
		return orderProductDetailList;
	}

	public List<OrderProduct> getOrderProductList() {
		return orderProductList;
	}

	public Orders getOrders() {
		return orders;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public Menu getPaymentTpMenu() {
		return paymentTpMenu;
	}

	public String getPaytype() {
		return paytype;
	}

	public String getPhone() {
		return phone;
	}

	public Product getProduct() {
		return product;
	}

	public int getProductCount() {
		return productCount;
	}

	public ProductService getProductService() {
		return productService;
	}

	public Menu getProductTpMenu() {
		return productTpMenu;
	}

	public String getProvince() {
		return province;
	}

	public TemplateService getVelocityService() {
		return velocityService;
	}

	public String getZipCode() {
		return zipCode;
	}

	/**
	 * @return the bankCodeMenu
	 */
	public Menu getBankCodeMenu() {
		return bankCodeMenu;
	}

	/**
	 * @param bankCodeMenu the bankCodeMenu to set
	 */
	public void setBankCodeMenu(Menu bankCodeMenu) {
		this.bankCodeMenu = bankCodeMenu;
	}

	private Orders pay(CartOrders cartOrders, String host, String channel, String storeId, String creditcardDetailId,
			String period) throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		Map addonInfo = new HashMap();
		String cpProductId = "";
		String cpUUID = "";
		boolean duplCouponProduct = false;
		if (StringUtils.isNotBlank(couponInfo)) {
			String[] dealCoupon = couponInfo.split(";");
			BigDecimal bcCoupon = BigDecimal.ZERO;
			for (int icp = 0; icp < dealCoupon.length; icp++) {
				String[] processCoupon = dealCoupon[icp].split(",");
				bcCoupon = bcCoupon.add(new BigDecimal(processCoupon[2].toString()));
			}
			cartOrders.setCoupon(bcCoupon);
		}
		if (couponInfo != null && couponInfo.length() > 0) {
			addonInfo.put("coupon", couponInfo);
		}
		addonInfo.put("remoteAddr", host);
		addonInfo.put("applySource", channel);
		addonInfo.put("promoteProduct", addCmpPd);
		addonInfo.put("domain", request.getServerName());
		addonInfo.put("channelChild", userData.getChChildCookie());
		addonInfo.put("storeId", storeId);

		String userAgent = request.getHeader("User-Agent");
		String bcookie = request.getHeader("Cookie");
		Map requestMap = request.getParameterMap();
		addonInfo.put("userAgent", userAgent);
		addonInfo.put("bcookie", bcookie);
		addonInfo.put("requestMap", JSONUtil.serialize(requestMap));

		cartOrders.setChannel(channel);
		if (addr.length() > 100) {
			addr = addr.substring(0, 100);
		}
		if (true == isInteger2(addr)) {
			logger.error("不允许全部数字输入:{}");
			throw new CartException("不允许全部数字输入！");
		}
		cartOrders.setReceiverAddr(addr);
		if ("※".equals(district.split(",")[0].substring(0, 1))) {
			district = district.split(",")[0].substring(1);
		} else {
			district = district.split(",")[0];
		}
		cartOrders.setReceiverArea(district);
		cartOrders.setReceiverCity(city);
		cartOrders.setReceiverExt(extension);
		cartOrders.setReceiverMobile(mobile);

		if (true == isInteger(contactName)) {
			logger.error("不允许数字输入:{}");
			throw new CartException("不允许数字输入！");
		}

		cartOrders.setReceiverName(contactName);
		cartOrders.setReceiverPhone(phone);
		cartOrders.setReceiverPhoneArea(areaCode);
		cartOrders.setReceiverProvince(province);
		cartOrders.setMemo(memo);
		if (zipCode.length() > 6) {
			zipCode = zipCode.substring(0, 6);
		}
		cartOrders.setReceiverZip(zipCode);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		Member member = memberService.get(memberId);
		if ("xx".equals(member.getSendEmail())) {
			cartOrders.setReceiverEmail(mail);
		}

		// 是否允许拆单
		if (cartOrders.getCartOrderProducts().size() > 1 && "Y".equals(allowSplit)) {
			cartOrders.setAllowSplit("Y");
		} else {
			cartOrders.setAllowSplit("N");
		}

		Map payment = new HashMap();
		payment.put("paymentType", paytype);
		payment.put("vrtBlnc", chkVrtBlnc);
		payment.put("giftCard", chkGiftCard);
		payment.put("bonus", editBonus);
		payment.put("creditcardDetailId", creditcardDetailId);
		payment.put("period", period);
		payment.put("editShipFare", editShipFare);

		if ("02".equals(cartOrders.getInvoiceTp())) {
			payment.put("invotype", cartOrders.getInvoiceTp());
			payment.put("invoTitle", cartOrders.getInvoiceTitle());
		}
		List<String> campaignList = new ArrayList<String>();
		if (null != reqMap) {
			campaigns = campaigns;
		}
		String[] campaignSplit = campaigns.split(",");
		for (String str : campaignSplit) {
			campaignList.add(str);
		}

		String hql = "from CampaignProduct where productId=?";
		Object[] cps = baseMgr.queryByHql(hql, new Object[] { addCmpPdId }, 0, 1);
		if (cps != null && cps.length > 0) {
			CampaignProduct cp = (CampaignProduct) cps[0];
			cartOrders = cartordersService.addPromoteProduct(cartOrders, cp.getUuid(), "5");

		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		cartOrders = cartordersService.calculateCart(cartOrders, optional, campaignList);
		// 订单成立时应只允许isDelete = 'N' 或 'H' 才能写入订单。
		Product productNH;
		for (CartOrderProduct cartOrderProd : cartOrders.getCartOrderProducts()) {
			productNH = productService.get(cartOrderProd.getProdId());
			if ("F".equals(productNH.getIsDelete()) || "Y".equals(productNH.getIsDelete())
					|| "Q".equals(productNH.getIsDelete())) {
				logger.error("商品销售状态不符, cartId:{}, cart product:{}, product:{}", new Object[] { cartOrders.getCartId(),
						cartOrderProd, productNH });
				throw new CartException("商品销售状态不符！");
			}
		}
		editTotalAmount = editTotalAmount.substring(0, editTotalAmount.indexOf(".") + 2);
		// System.out.println(finalTotalAmount);
		BigDecimal amountFromPage = new BigDecimal((editTotalAmount));

		BigDecimal cartSumAmount = cartOrders.getAmount().add(cartOrders.getDiscount());

		// 积分檢查-会员是否有积分
		Balance balance = member.getBalance();
		if (new BigDecimal(editBonus).compareTo(balance.getBonusBalance()) == 1) {
			logger.error("cart.id:{}, 折抵积分>会员积分, editBonus:{}. balance:{}", new Object[] { cartOrders.getCartId(), editBonus,
					balance.getBonusBalance() });
			throw new CartException("折抵积分>会员积分！");
		}
		BigDecimal iOffset = orderService.calcOffsetBonus(request.getServerName(), userData.getApplySource(), member
				.getBalance(), cartOrders.getAmount());// 计算积分折抵上限

		// 积分檢查-折抵积分與实际折抵积分 不可差異大于1
		BigDecimal pageBonus = new BigDecimal(editBonus);
		if (iOffset.subtract(pageBonus).floatValue() < -1.0) {
			logger.error("cart.id:{}, 折抵积分>实际折抵积分, iOffset:{}. editBonus:{}", new Object[] { cartOrders.getCartId(), iOffset,
					editBonus });
			throw new CartException("折抵积分>实际折抵积分！");
		}
		// 账户余额检查chkVrtBlnc
		if (new BigDecimal(chkVrtBlnc).compareTo(member.getBalance().getVirtualBalance()) == 1) {
			logger.error("cart.id:{}, 我的账户余额>实际我的账户余额,chkVrtBlnc:{}, memberVirtualBalance: {}", new Object[] {
					cartOrders.getCartId(), chkVrtBlnc, member.getBalance().getVirtualBalance() });
			throw new CartException("我的账户余额>实际我的账户余额！");
		}
		// 礼品卡馀额检查chkGiftCard
		if (new BigDecimal(chkGiftCard).compareTo(member.getBalance().getGiftcardBalance()) == 1) {
			logger.error("cart.id:{}, 我的礼品卡余额>实际我的礼品卡余额,chkGiftCard:{}, memberGiftCardBalance: {}", new Object[] {
					cartOrders.getCartId(), chkGiftCard, member.getBalance().getGiftcardBalance() });
			throw new CartException("我的礼品卡余额>实际我的礼品卡余额！");
		}
		// 剩余应付金额不可为负值
		if (new BigDecimal(editTotalAmount).compareTo(BigDecimal.ZERO) == -1) {
			logger.error("cart.id:{}, 剩余应付金额<,editTotalAmount:{}", editTotalAmount);
			throw new CartException("剩余应付金额<0！");
		}
		if (cartOrders.getCartOrderProducts() == null || cartOrders.getCartOrderProducts().size() == 0
				|| Math.abs(cartSumAmount.subtract(amountFromPage).floatValue()) != 0) {
			logger.error("cart:{}, cart products:{}, cart.sum:{}, amountFromPage:{}", new Object[] { cartOrders,
					cartOrders.getCartOrderProducts(), cartSumAmount, amountFromPage });
			throw new CartException("订单金额与预期不符，请检查购物车！");
		}

		// 手机验证
		if ("on".equals(ServerValue.getBlockOrderPaymentType())) {
			if ("10".equals(paytype) || "20".equals(paytype) || "30".equals(paytype) || "60".equals(paytype)) {
				if ("nonmember".equals(member.getApplySource())) {
					throw new CartException("会员功能限耀点100会员使用");
				}
				if (member.getIsMobileMember() == false) {
					throw new CartException("手机验证錯誤");
				}
			}
		}
		// 不允许cod付款
		if (!"on".equals(ServerValue.getUseCod())) {
			if (Arrays.asList("30", "60").contains(paytype)) {
				throw new CartException("不允许COD付款");
			}
		}

		Orders result = null;
		boolean retry = true;
		int count = 0;
		do {
			try {
				count++;
				result = orderService.createOrderWithPay(cartOrders, addonInfo, payment);
				retry = false;
			} catch (Exception e) {
				logger.error("fail " + count + " times, cart:" + cartOrders, e);
				Thread.sleep(100);
				CartOrders tmp = cartordersService.getCart(cartOrders.getMemberId(), cartOrders.getCartId());
				if (tmp == null || !tmp.getModifyDate().equals(cartOrders.getModifyDate())
						|| "error.coupon.isused".equals(e.getMessage())) {
					throw new CartException("订单已经建立，请检查最近订单明细！");
				} else if ("errors.order.address.not.match".equals(e.getMessage())) {
					throw new CartException("地址资料不符合！");
				} else if ("errors.order.badman".equals(e.getMessage())) {
					throw new CartException("您的帐号异常, 请洽客服人员");
				} else if (e.getMessage() != null
						&& (e.getMessage().startsWith("error.coupon.") || e.getMessage().startsWith("error.order.") || e
								.getMessage().startsWith("error.payment."))) {
					// 丟這幾個開頭, 都是資料異常, 可以考慮丟到黑名單
					throw new CartException("订单建立失败！");
				} else if (e.getMessage().startsWith("订单毛利率不符合")) {
					String mailBody = e.getMessage().split("＠")[1];
					if (StringUtils.isNotBlank(mailBody)) {
						Mail mail = new Mail("订单防火墙通知信-前台订购", e.getMessage().split("＠")[1], systemValueMenu.getOptions().get(
								"fw_mail").getMemo1(), "");
						mail.setBcc("feeling.wang@yaodian100.com");
						mailService.save(mail);
					}
					if (tmp.getCartId().equals(tmp.getMemberId())) {
						throw new CartException("抱歉<br>请重新选购!,cart");
					} else {
						throw new CartException("抱歉<br>请重新选购!,buy");
					}
				} else if (e.getMessage().startsWith("积分检查不过")) {
					String mailBody = e.getMessage().split("＠")[1];
					if (StringUtils.isNotBlank(mailBody)) {
						Mail mail = new Mail("订单积分检查不过通知信", e.getMessage().split("＠")[1], "fe@yaodian100.com", "");
						mailService.save(mail);
					}
					throw new CartException("订单建立失败！");
				} else if (e.getMessage().startsWith("金额异常＠")) {
					String mailSubject = e.getMessage().split("＠")[1];
					String mailBody = e.getMessage().split("＠")[2];
					if (StringUtils.isNotBlank(mailSubject)) {
						Mail mail = new Mail(mailSubject, mailBody, "fe@yaodian100.com", "");
						mailService.save(mail);
					}
					throw new CartException("订单建立失败！");
				} else if (e.getMessage().startsWith("金额异常＠")) {
					String mailSubject = e.getMessage().split("＠")[1];
					String mailBody = e.getMessage().split("＠")[2];
					if (StringUtils.isNotBlank(mailSubject)) {
						Mail mail = new Mail(mailSubject, mailBody, "fe@yaodian100.com", "");
						mailService.save(mail);
					}
					throw new CartException("订单建立失败！");
				} else if (count > 4) {
					throw new CartException("订单建立失败，请检查购物车！");
				}
			}
		} while (retry);
		return result;
		// return null;

	}

	public String paymentInfo() throws Exception {
		if (null != reqMap) {
			reqMap = reqMap.replace("[", "");
			reqMap = reqMap.replace("]", "");
			reqMap = reqMap.replace("/", "");
			campaigns = JSONObject.fromObject(reqMap).get("campaigns").toString();
			addCmpPdId = JSONObject.fromObject(reqMap).get("addCmpPdId").toString();
			editTotalAmount = JSONObject.fromObject(reqMap).get("editTotalAmount").toString();
			editBonus = JSONObject.fromObject(reqMap).get("editBonus").toString();
			editCoupon = JSONObject.fromObject(reqMap).get("editCoupon").toString();
			editShipFare = JSONObject.fromObject(reqMap).get("editShipFare").toString();
			phone = JSONObject.fromObject(reqMap).get("phone").toString();
			addCmpPd = JSONObject.fromObject(reqMap).get("addCmpPd").toString();
			addr = JSONObject.fromObject(reqMap).get("addr").toString();
			finalTotalAmount = JSONObject.fromObject(reqMap).get("finalTotalAmount").toString();
			city = JSONObject.fromObject(reqMap).get("city").toString();
			zipCode = JSONObject.fromObject(reqMap).get("zipCode").toString();
			paytype = JSONObject.fromObject(reqMap).get("paytype").toString();
			province = JSONObject.fromObject(reqMap).get("province").toString();
			couponInfo = JSONObject.fromObject(reqMap).get("couponInfo").toString();
			district = JSONObject.fromObject(reqMap).get("district").toString();
			mail = JSONObject.fromObject(reqMap).get("mail").toString();
			areaCode = JSONObject.fromObject(reqMap).get("areaCode").toString();
			extension = JSONObject.fromObject(reqMap).get("extension").toString();
			contactName = JSONObject.fromObject(reqMap).get("contactName").toString();
			mobile = JSONObject.fromObject(reqMap).get("mobile").toString();
			allowSplit = JSONObject.fromObject(reqMap).get("allowSplit").toString();
			if (null != JSONObject.fromObject(reqMap).get("chkVrtBlnc")) {
				chkVrtBlnc = JSONObject.fromObject(reqMap).get("chkVrtBlnc").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("chkGiftCard")) {
				chkGiftCard = JSONObject.fromObject(reqMap).get("chkGiftCard").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("chkCoupon")) {
				chkCoupon = JSONObject.fromObject(reqMap).get("chkCoupon").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("chkBonus")) {
				chkBonus = JSONObject.fromObject(reqMap).get("chkBonus").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("buyNowCartId")) {
				buyNowCartId = JSONObject.fromObject(reqMap).get("buyNowCartId").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("storeId")) {
				storeId = JSONObject.fromObject(reqMap).get("storeId").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("ccode")) {
				ccode = JSONObject.fromObject(reqMap).get("ccode").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("creditcardDetailId")) {
				creditcardDetailId = JSONObject.fromObject(reqMap).get("creditcardDetailId").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("editPeriod")) {
				editPeriod = JSONObject.fromObject(reqMap).get("editPeriod").toString();
			}
			if (null != JSONObject.fromObject(reqMap).get("invoTitle")) {
				if ("02".equals(JSONObject.fromObject(reqMap).get("invotype").toString())) {
					invotype = JSONObject.fromObject(reqMap).get("invotype").toString();
					invoTitle = JSONObject.fromObject(reqMap).get("invoTitle").toString();
				}
			}
			if (null != JSONObject.fromObject(reqMap).get("editPeriodAmount")) {
				editPeriodAmount = JSONObject.fromObject(reqMap).get("editPeriodAmount").toString();
			}
		}
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String currentCartId = userData.readRawValue("cartid");
		String memberId = StringUtils.defaultString(userData.getMemberId());
		Member member = memberService.get(memberId);
		if (buyNowCartId != null && buyNowCartId.length() > 0) {
			currentCartId = buyNowCartId;
			rsPage = "buy";
		} else {
			if (memberId != null) {
				currentCartId = memberId;
				rsPage = "cart";
			}
		}
		// if (null != reqMap && buyNowCartId != null && buyNowCartId.length() > 0) {
		// currentCartId = buyNowCartId;
		// } else {
		// currentCartId = memberId;
		// }

		if (StringUtils.isNotBlank(currentCartId)) {
			/* 若商品需要验证码，则判断验证码是否正确 */
			if (cartordersService.needValidateNum(currentCartId)) {
				if (null != userData.getImageValid() && StringUtils.isNotBlank(userData.getImageValid())) {
					if (null == ccode || StringUtils.isBlank(ccode)) {
						addActionMessage("验证码参数错误," + rsPage);
						return "paymentInfo";
					}
					try {
						cartOrderService.checkCode(userData.getImageValid(), ccode);
					} catch (Exception e) {
						addActionMessage("验证码输入不正确," + rsPage);
						return "paymentInfo";
					}
				}
			}
			// 呼叫購物車 ／／
			CartOrders cartOrders = cartordersService.getCart(memberId, currentCartId);
			String cpItemUUID = "";
			if (StringUtils.isNotBlank(couponInfo)) {
				String[] processCoupon = couponInfo.split(",");
				cpItemUUID = processCoupon[3];
			}
			if (null == chkVrtBlnc) {
				chkVrtBlnc = "0.00";
			}
			if (null == chkGiftCard) {
				chkGiftCard = "0.00";
			}
			// 禮券或积分的checkbox都有勾選或禮券使用金額&积分金額都有被使用
			if (StringUtils.equalsIgnoreCase("single", ServerValue.getDiscountType())) {
				if ((null != chkCoupon && null != chkBonus)
						|| (new BigDecimal(editBonus).compareTo(new BigDecimal(0)) == 1 && new BigDecimal(editCoupon)
								.compareTo(new BigDecimal(0)) == 1)) {
					addActionMessage("礼券或积分，请择一使用," + rsPage);
					return "paymentInfo";
				}
			}
			try {
				String host = request.getHeader("X-Forwarded-For");
				if (StringUtils.isBlank(host)) {
					host = StringUtils.defaultString(request.getRemoteAddr(), "0.0.0.0");
				} else if (host.length() > 100) {
					host = host.substring(0, 100);
				}

				int chId = 0;
				if (StringUtils.isNotBlank(userData.readValue("ch_id"))) {
					chId = Integer.parseInt(userData.readValue("ch_id"));
				} else {
					chId = channelService.getActivateChannelIdByName(userData.getApplySource()).intValue();
				}
				cartOrders.setChannelSeq(chId);

				// 记录达夫妮门店cookie
				if (StringUtils.isNotBlank(storeId)) {
					// 未滿一定金額無法使用店取貨
					if (cartOrders.getAmount().compareTo(ServerValue.getDaphneLimitPrice()) != 1) {
						addActionMessage("notSupport");
						return "paymentInfo";
					}
					userData.writeRawValue("storeId", storeId);
				}

				if (StringUtils.isNotBlank(contactName)) {
					StringBuffer sbReceiver = new StringBuffer();
					sbReceiver.append(StringUtils.defaultString(contactName)).append(",");
					sbReceiver.append(StringUtils.defaultString(areaCode)).append(",");
					sbReceiver.append(StringUtils.defaultString(phone)).append(",");
					sbReceiver.append(StringUtils.defaultString(extension)).append(",");
					sbReceiver.append(StringUtils.defaultString(mobile));
					userData.writeRawValue("receiverData", new String(Base64.encode(sbReceiver.toString().getBytes())));
				}

				// 限時搶購
				if (null != timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts())) {
					try {
						// 判斷是否cookie從商品頁的購物車
						String timeLimitCookie = userData.readRawValue(UserData.NAME_YAODIAN100_TL_RS);
						if (StringUtils.isNotBlank(timeLimitCookie)) {
							String tlpId;
							if (timeLimitCookie.indexOf("/shopping/cart.do") >= 0) {
								tlpId = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
								if (!"2".equals(tlpId)) {
									addActionMessage(tlpId);
									return "paymentInfo";
								}
							} else {
								// 判斷是否cookie從商品頁的立即購買或達芙妮
								String timeLimitProductId = timeLimitCookie.substring(timeLimitCookie.lastIndexOf("=") + 1);
								if (StringUtils.isNotBlank(timeLimitProductId)) {
									tlpId = timeLimitSaleService.canBuy(timeLimitProductId, memberId);
									if (!"2".equals(tlpId)) {
										addActionMessage(tlpId);
										return "paymentInfo";
									}
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						addActionMessage("数量不足或资料错误");
						return "paymentInfo";
					}
				}

				Product iproduct = null;
				Specification ispec = null;
				SpecificationInventory ispecInv = null;

				// 訂購流程_商品&赠品不足之检查
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				optional.put("rsPage", rsPage);
				String acp = "";
				if (addCmpPd != null) {
					acp = StringUtils.defaultString(addCmpPd);
				}
				String invntryInfo = cartordersService.checkSpecInventory(currentCartId, acp, optional, "step2");
				if (!"OK".equals(invntryInfo)) {
					if (null != reqMap) {
						cartOrderProductDetailList = new ArrayList();
						for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
							cartOrderProductDetailList.addAll(cop.getDetails());
						}
						String isBuyNow = JSONObject.fromObject(reqMap).get("isBuyNow").toString().substring(0, 1);
						for (CartOrderProductDetail copd_ : cartOrderProductDetailList) {
							SpecificationInventory specificationInventory = new SpecificationInventory();
							CommonCriteria criteria = new CommonCriteria();
							criteria.addEq("productId", copd_.getProdId());
							criteria.addEq("specId", Long.parseLong(copd_.getProdSpecId()));
							specificationInventory = productService.getSpecificationInventory(copd_.getProdId(), Long.parseLong(copd_
									.getProdSpecId()));
							int availableInventory = specificationInventory.getInventory();
							Specification spec = (Specification) baseMgr
									.get(Specification.class, Long.valueOf(copd_.getProdSpecId()));
							// 找主商品的购物车数量
							CartOrderProduct cop = (CartOrderProduct) baseMgr.get(CartOrderProduct.class, copd_.getCartOrderProdId());
							if (copd_.getDetailTp().equals("2") && null == copd_.getCartOrderProdId()) {// 活动赠品
								if (availableInventory < copd_.getQty()) {
									baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?",
											new Object[] { availableInventory, copd_.getCartOrderDetailId() });
								} else if (availableInventory <= 0) {
									baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderDetailId=?",
											new Object[] { copd_.getCartOrderDetailId() });
								}
							} else if ("2".equals(copd_.getDetailTp())) {
								if (copd_.getQty() > cop.getQty()) {
									baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?",
											new Object[] { cop.getQty(), copd_.getCartOrderDetailId() });
								} else if (availableInventory < copd_.getQty()) {
									baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?",
											new Object[] { availableInventory, copd_.getCartOrderDetailId() });
								} else if (availableInventory <= 0) {
									baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderDetailId=?",
											new Object[] { copd_.getCartOrderDetailId() });
								}
							}
						}
						List<String> campaignList = new ArrayList<String>();
						String[] campaignSplit = campaigns.split(",");
						for (String str : campaignSplit) {
							campaignList.add(str);
						}
						cartOrders = cartordersService.getCart(memberId, currentCartId);
					} else {
						reqMap = JSONUtil.serialize(request.getParameterMap());
						addActionMessage(invntryInfo);
						return "paymentInfo";
					}
				}
				// 404問題: 訂單商品數量超訂現象
				/*
				 * for (CartOrderProduct cop_ : cartOrders.getCartOrderProducts()) { iproduct =
				 * productService.get(cop_.getProdId()); ispec =
				 * productService.getSpecification(Long.parseLong(cop_.getProdSpecId())); if (iproduct.getProductType() != 6) {
				 * ispecInv = productService.getSpecificationInventory(cop_.getProdId(), ispec.getSpecificationId()); }
				 * cop_.setQty(cartordersService.checkSpecInvReturnQty(iproduct, ispec, ispecInv, cop_.getQty())); }
				 * cartOrderProductDetailList = new ArrayList(); for (CartOrderProduct cop : cartOrders.getCartOrderProducts())
				 * { cartOrderProductDetailList.addAll(cop.getDetails()); } for (CartOrderProductDetail copd_ :
				 * cartOrderProductDetailList) { iproduct = productService.get(copd_.getProdId()); ispec =
				 * productService.getSpecification(Long.parseLong(copd_.getProdSpecId())); if (iproduct.getProductType() != 6) {
				 * ispecInv = productService.getSpecificationInventory(copd_.getProdId(), ispec.getSpecificationId()); }
				 * copd_.setQty(cartordersService.checkSpecInvReturnQty(iproduct, ispec, ispecInv, copd_.getQty())); }
				 */

				// 信用卡分期(限立即購買)
				if ("80".equals(paytype) && !cartOrders.getMemberId().equals(cartOrders.getCartId())) {
					String tmpProdId = "";
					for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
						if (Arrays.asList("0", "1", "6", "7").contains(cop.getProdTp())) {// 商品type為一般、預購、nm主商品
							tmpProdId = cop.getProdId();
						}
					}
					creditcardDetail = creditcardService.getValidCreditcard(tmpProdId, creditcardDetailId, editPeriod, userData
							.getApplySource(), request.getServerName());
					if (null == creditcardDetail) {
						throw new CartException("订单选择之信用卡分期支付方式不符活动规则，请重新结帐。");
					}
					if (null != creditcardDetail.getAmountLimits()) {
						Map<String, List<Float>> periodMap = creditcardDetail.getAmountLimits();// List [上限金额, 下限金额]
						if (null == periodMap.get(editPeriod) || Float.valueOf(editTotalAmount) < periodMap.get(editPeriod).get(0)
								|| Float.valueOf(editTotalAmount) > periodMap.get(editPeriod).get(1)) {// 不符合分期期數的上下限
							throw new CartException("订单选择之信用卡分期支付方式不符活动规则，请重新结帐。");
						}
					} else {
						throw new CartException("结帐金额未达分期最低金额限制，请重新选择付款方式。");
					}
					cartOrders.setCreditcardDetail(creditcardDetail);
					cartOrders.setPeriod(editPeriod);
				}
				cartOrders.setInvoiceTp(invotype);
				cartOrders.setInvoiceTitle(invoTitle);
				orders = pay(cartOrders, host, userData.getApplySource(), StringUtils.defaultString(storeId), StringUtils
						.defaultString(creditcardDetailId), StringUtils.defaultString(editPeriod));
				orderId = orders.getOrderId();
				orderInfoView = orderInfoView + orders.getOrderId() + "&channelFlag=Y";
			} catch (CartException e) {
				cartMessage = e.getMessage();
				if (StringUtils.contains(cartMessage, "抱歉<br>请重新选购!")) {
					addActionMessage(cartMessage);
					return "paymentInfo";
				} else {
					return "returnToCart";
				}
			} catch (Exception e) {
				e.printStackTrace();
				addActionMessage("数量不足或资料错误");
				return "paymentInfo";
			}
			if (null != orders) {
				// 前端顯示訂單資訊
				showOrderDetail(orders.getOrderId());
				setOrderId(orders.getOrderId());
				// 清除cookie
				userData.clear("cartid");
				String timeLimitCookie = userData.readRawValue(UserData.NAME_YAODIAN100_TL_RS);
				if (StringUtils.isNotBlank(timeLimitCookie)) {
					if (timeLimitCookie.indexOf("/shopping/cart.do") >= 0) {
						userData.writeRawValue(userData.NAME_YAODIAN100_CART_ITEMS, "0");
					}
				}
				logService.save(getClass().getSimpleName(), "paymentInfo", orders);

			}
			// logger.error("orders.getMemo()1::::{}", orders.getMemo());
			// if (StringUtils.isNotBlank(orders.getMemo())) {
			// if (orders.getMemo().indexOf("异常") >= 0) {
			// orderMemoAlert = "orderMemoAlert";
			// logger.error("orderMemoAlert::::{}", orderMemoAlert);
			// }
			// } else {
			// orderMemoAlert = "";
			// }
		}
		return "paymentInfoBuyNow";
	}

	private Orders pay(CartOrders cartOrders, String host, String channel, String storeId) throws Exception {
		return pay(cartOrders, host, channel, storeId, "", "");
	}

	public String paymentInfoView() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		HttpSession session = request.getSession();
		UserData userData = new UserData(request, response);
		member = memberService.get(userData.getMemberId());
		if (null != userData && null != userData.getMemberId()) {
			showOrderDetail(orderId);
			if (userData.getMemberId().equals(orders.getMemberId())) {
				// for channel
				logger.info("getChannelFlag()::{}", getChannelFlag());
				if (getChannelFlag().equals("Y")) {
					List<String> odList = orderService.getChannelList(orders.getOrderId());
					String channel = orders.getChannel().indexOf("_") == -1 ? orders.getChannel() : orders.getChannel()
							.split("_")[0];
					ChannelTemplate template = channelService.getAvailableChannelTemplate(channel, "CPS");
					Map<String, Object> objs = new HashMap<String, Object>();
					objs.put("odList", odList);
					objs.put("orders", orders);
					gwdScript = "";// velocityService.format("order.gwdScript", objs);
					if (null != template) {
						objs.put("childMap", channelService.splitChild(orders.getChannel_child()));
						objs.put("createDate", new DateTool().format(EcConstant.PATTERN_TIMESTAMP, orders.getCreateDate()));
						Map<String, BigDecimal> priceMap = new HashMap<String, BigDecimal>();
						if ("fanli".equals(channel)) {
							countFanliRate(odList, priceMap, orders);
						}
						objs.put("priceMap", priceMap);
						channelResult = velocityService.formatByStringTemplate(template.getContents(), objs);
					}
					if (channelResult == null) {
						channelResult = "";
					}
					if (channelResult.length() != 0) {
						channelResult += "\r\n";
					}
					channelResult += this.getMvsiteChannelResult(odList, orders);
				}
				// co-branding action
				try {
					String domainSrc = orders.getDomainSrc();
					if (!domainSrc.endsWith("yaodian100.com")) {
						if (domainSrc.endsWith("onlylady.com")) {
							Onlylady ol = new Onlylady();
							ol.olCreateOrder(orders);
						}
					}
				} catch (Exception e) {

					// e.printStackTrace();
				}

				List<OrderProduct> orderProducts = orders.getOrderProduct();

				if (null != orderProducts) {
					// 百分点推荐引擎sessionid
					String sessionId = userData.getSessionId();
					if (null == sessionId || StringUtils.isBlank(sessionId)) {
						userData.writeValue(UserData.NAME_YAODIAN100_SESSION_ID, session.getId());
					}
					// 宇匯商品推荐
					StringBuffer sbItem = new StringBuffer();
					// 百分點商品推薦
					StringBuffer sb100Item = new StringBuffer();
					List<String> itProdType = Arrays.asList("0", "1", "6", "7");
					int i = 1;
					for (OrderProduct opItem : orderProducts) {
						if (itProdType.contains(opItem.getProdTp())) {
							sbItem.append(opItem.getProdId()).append(",").append(opItem.getUnitPrice()).append(",").append(
									opItem.getQty()).append(",");
						}
						if (opItem.getUnitPrice().compareTo(BigDecimal.ZERO) == 1) {
							sb100Item.append("p.p").append(i).append(" = new brs.PurchaseItem(");
							sb100Item.append("'").append(orders.getMemberId()).append("',");
							sb100Item.append("'").append(opItem.getProdId()).append("',");
							sb100Item.append("'").append(userData.getSessionId()).append("',");
							sb100Item.append("'").append(opItem.getUnitPrice()).append("',");
							sb100Item.append("'").append(opItem.getQty()).append("'");
							sb100Item.append(");\n");
							sb100Item.append("p.p").append(i).append(".order_id ='").append(orders.getOrderId()).append("';\n");
							i++;
						}
					}
					if (sbItem.length() > 0) {
						bitem = sbItem.substring(0, sbItem.length() - 1);
					}
					if (sb100Item.length() > 0) {
						b100item = sb100Item.toString();
					}
				}
				if (StringUtils.isNotBlank(orders.getMemo())) {
					if (orders.getMemo().indexOf("异常") >= 0) {
						orderMemoAlert = "orderMemoAlert";
						logger.error("orderMemoAlert::::{}", orderMemoAlert);
					}
				} else {
					orderMemoAlert = "";
				}
				// 大材积商品
				prodVolumeMap = orderService.chkVolumeOfOrderDetail(orders.getOrderId());
				return "paymentInfo";
			} else {
				return "index";// 导回首页
			}
		} else {
			return "index";// 导回首页
		}
	}

	private String getMvsiteChannelResult(List<String> odList, Orders orders) {
		try {
			String channel = "mvsite";
			Menu orderStatus = menuService.get("Order.status");
			String orderSt = orderStatus.getOptions().get(orders.getOrderSt()).getName();
			ChannelTemplate template = channelService.getAvailableChannelTemplate(channel, "CPS");
			Map<String, Object> objs = new HashMap<String, Object>();
			objs.put("odList", odList);
			objs.put("orders", orders);
			objs.put("orderSt", orderSt);
			if (null != template) {
				String result = velocityService.formatByStringTemplate(template.getContents(), objs);
				return result;
			} else {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private void countFanliRate(List<String> odList, Map<String, BigDecimal> priceMap, Orders orders) {
		Map<String, Option> rateOption = rateMenu.getOptions();
		Object[] obj = odList.toArray();
		boolean useMemo2 = false;
		if (orders.getBonus().floatValue() > 0) {
			useMemo2 = true;
		}
		for (int iOd = 0; iOd < obj.length; iOd++) {
			Object[] obj2 = (Object[]) obj[iOd];
			String rate = "0.03";
			Option o = rateOption.get(obj2[3].toString().split("/")[0]);
			if (null != o) {
				if (useMemo2 && StringUtils.isNotBlank(o.getMemo2())) {
					rate = o.getMemo2();
				} else {
					if (!obj2[5].toString().equals(obj2[6].toString())) {
						rate = o.getMemo2();
					} else {
						rate = o.getMemo1();
					}
				}
			}
			priceMap.put(obj2[0].toString(), new BigDecimal(obj2[2].toString()).multiply(new BigDecimal(rate)).setScale(2,
					BigDecimal.ROUND_HALF_UP));
		}
	}

	public void prepare() throws Exception {
		if (paymentTpMenu == null) {
			paymentTpMenu = menuService.get("Order.PaymentTp");
		}
		if (productTpMenu == null) {
			productTpMenu = menuService.get("Product.Type");
		}
		if (rateMenu == null) {
			rateMenu = menuService.get("Fanli.Rate");
		}
		if (bankCodeMenu == null) {
			bankCodeMenu = menuService.get("Payment.3rdPartyBank");
		}
		if (paymentSrcMenu == null) {
			paymentSrcMenu = menuService.get("Payment.Src");
		}
		if (null == systemValueMenu) {
			systemValueMenu = menuService.get("SystemValue");
		}
	}

	/**
	 * 列印
	 * 
	 * @return
	 * @throws Exception
	 */
	public String printOrder() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		member = memberService.get(userData.getMemberId());
		orders = orderService.get(orderId);
		// 計算商品數

		String hql = "from OrderProductDetail where orderId=? and detailTp!=?";
		productCount = baseMgr.countByHql(hql, new Object[] { orderId, "2" }).intValue();
		if (null != orders) {
			if (orders.getOrderProduct().get(0).getProdTp().equals("1")) {
				product = productService.get(orders.getOrderProduct().get(0).getProdId());
			}
		}
		if ("80".equals(orders.getPaymentTp())) {// 信用卡分期付款
			creditcard = creditcardService.get(orders.getOrderCreditCardCampaign().getCreditcardId());
			billBankCodeMenu = menuService.get("99Bill.BankCode");
		}
		if ("70".equals(orders.getPaymentTp())) {// 信用放單期付款
			billBankSingleCodeMenu = menuService.get("99BillSingle.BankCode");
		}

		return "printOrder";
	}

	public void setAddCmpPd(String addCmpPd) {
		this.addCmpPd = addCmpPd;
	}

	/**
	 * @param addCmpPdId the addCmpPdId to set
	 */
	public void setAddCmpPdId(String addCmpPdId) {
		this.addCmpPdId = addCmpPdId;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public void setAdwaysInfo(String adwaysInfo) {
		this.adwaysInfo = adwaysInfo;
	}

	public void setAreaCode(String areaCode) {
		this.areaCode = areaCode;
	}

	/**
	 * @param buyNowCartId the buyNowCartId to set
	 */
	public void setBuyNowCartId(String buyNowCartId) {
		this.buyNowCartId = buyNowCartId;
	}

	public void setBuyNowInfo(String[] buyNowInfo) {
		this.buyNowInfo = buyNowInfo;
	}

	/**
	 * @param campaigns the campaigns to set
	 */
	public void setCampaigns(String campaigns) {
		this.campaigns = campaigns;
	}

	/**
	 * @param cartMessage the cartMessage to set
	 */
	public void setCartMessage(String cartMessage) {
		this.cartMessage = cartMessage;
	}

	public void setCartOrderProductDetailList(List<CartOrderProductDetail> cartOrderProductDetailList) {
		this.cartOrderProductDetailList = cartOrderProductDetailList;
	}

	public void setCartOrderProductList(List<CartOrderProduct> cartOrderProductList) {
		this.cartOrderProductList = cartOrderProductList;
	}

	public void setCartordersService(CartOrdersService cartordersService) {
		this.cartordersService = cartordersService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public void setChannelFlag(String channelFlag) {
		this.channelFlag = channelFlag;
	}

	public void setChannelResult(String channelResult) {
		this.channelResult = channelResult;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

	public void setChkVrtBlnc(String chkVrtBlnc) {
		this.chkVrtBlnc = chkVrtBlnc;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public void setContactName(String contactName) {
		this.contactName = contactName;
	}

	public void setCouponInfo(String couponInfo) {
		this.couponInfo = couponInfo;
	}

	public void setCouponService(CouponService couponService) {
		this.couponService = couponService;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public void setEditBonus(String editBonus) {
		this.editBonus = editBonus;
	}

	public void setEditShipFare(String editShipFare) {
		this.editShipFare = editShipFare;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

	/**
	 * @param finalTotalAmount the finalTotalAmount to set
	 */
	public void setFinalTotalAmount(String finalTotalAmount) {
		this.finalTotalAmount = finalTotalAmount;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public void setOrderInfoView(String orderInfoView) {
		this.orderInfoView = orderInfoView;
	}

	public void setOrderProduct(OrderProduct orderProduct) {
		this.orderProduct = orderProduct;
	}

	public void setOrderProductDetail(OrderProductDetail orderProductDetail) {
		this.orderProductDetail = orderProductDetail;
	}

	public void setOrderProductDetailList(List<OrderProductDetail> orderProductDetailList) {
		this.orderProductDetailList = orderProductDetailList;
	}

	public void setOrderProductList(List<OrderProduct> orderProductList) {
		this.orderProductList = orderProductList;
	}

	public void setOrders(Orders orders) {
		this.orders = orders;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public void setPaymentTpMenu(Menu paymentTpMenu) {
		this.paymentTpMenu = paymentTpMenu;
	}

	public void setPaytype(String paytype) {
		this.paytype = paytype;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public void setProductCount(int productCount) {
		this.productCount = productCount;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setProductTpMenu(Menu productTpMenu) {
		this.productTpMenu = productTpMenu;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public void setTransferService(TransferService transferService) {
		this.transferService = transferService;
	}

	public void setVelocityService(TemplateService velocityService) {
		this.velocityService = velocityService;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	// 前端顯示訂單資訊
	void showOrderDetail(String orderId) {
		orders = orderService.get(orderId);
		String hql = "from OrderProductDetail where orderId=? and detailTp!=?";
		productCount = baseMgr.countByHql(hql, new Object[] { orderId, "2" }).intValue();
		if (null != orders) {
			if (!orders.getOrderId().equals(orders.getJoinOrders())) {
				joinOrderList = new ArrayList();
				String[] splitOrderId = StringUtils.split(orders.getJoinOrders(), ",");
				for (String oId : splitOrderId) {
					Orders joinOrder = orderService.get(oId);
					// BigDecimal totalprice = BigDecimal.ZERO;
					// totalprice = order.getTotalPrice().subtract(order.getBonus()).subtract(order.getCoupon()).add(
					// order.getShipfare()).subtract(order.getDiscount()).add(order.getCodFee()).add(order.getInstallmentFee());
					joinOrderList.add(joinOrder);
				}
			}
			if (orders.getOrderProduct().get(0).getProdTp().equals("1")) {
				product = productService.get(orders.getOrderProduct().get(0).getProdId());
			}
			if ("80".equals(orders.getPaymentTp())) {// 信用卡分期付款
				creditcard = creditcardService.get(orders.getOrderCreditCardCampaign().getCreditcardId());
				billBankCodeMenu = menuService.get("99Bill.BankCode");
			}
			if ("70".equals(orders.getPaymentTp())) {// 信用放單期付款
				billBankSingleCodeMenu = menuService.get("99BillSingle.BankCode");
			}
		}
	}

	public String getStoreId() {
		return storeId;
	}

	public void setStoreId(String storeId) {
		this.storeId = storeId;
	}

	public void setTimeLimitSaleService(TimeLimitSaleService timeLimitSaleService) {
		this.timeLimitSaleService = timeLimitSaleService;
	}

	public String getBitem() {
		return bitem;
	}

	public void setBitem(String bitem) {
		this.bitem = bitem;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public String getReqMap() {
		return reqMap;
	}

	public void setReqMap(String reqMap) {
		this.reqMap = reqMap;
	}

	public String getCanUse() {
		return canUse;
	}

	public void setCanUse(String canUse) {
		this.canUse = canUse;
	}

	public String getChkCoupon() {
		return chkCoupon;
	}

	public void setChkCoupon(String chkCoupon) {
		this.chkCoupon = chkCoupon;
	}

	public String getChkBonus() {
		return chkBonus;
	}

	public void setChkBonus(String chkBonus) {
		this.chkBonus = chkBonus;
	}

	public String getEditCoupon() {
		return editCoupon;
	}

	public void setEditCoupon(String editCoupon) {
		this.editCoupon = editCoupon;
	}

	public String getGwdScript() {
		return gwdScript;
	}

	/**
	 * @return the paymentSrcMenu
	 */
	public Menu getPaymentSrcMenu() {
		return paymentSrcMenu;
	}

	/**
	 * @param paymentSrcMenu the paymentSrcMenu to set
	 */
	public void setPaymentSrcMenu(Menu paymentSrcMenu) {
		this.paymentSrcMenu = paymentSrcMenu;
	}

	// check contactName
	public boolean isInteger(String input) {
		try {
			Integer.parseInt(input);
			if (input.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	// check addr
	public boolean isInteger2(String input) {
		try {
			Integer.parseInt(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public String getCcode() {
		return ccode;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public String getOrderMemoAlert() {
		return orderMemoAlert;
	}

	public void setOrderMemoAlert(String orderMemoAlert) {
		this.orderMemoAlert = orderMemoAlert;
	}

	public Creditcard getCreditcard() {
		return creditcard;
	}

	public void setCreditcard(Creditcard creditcard) {
		this.creditcard = creditcard;
	}

	public CreditcardDetail getCreditcardDetail() {
		return creditcardDetail;
	}

	public void setCreditcardDetail(CreditcardDetail creditcardDetail) {
		this.creditcardDetail = creditcardDetail;
	}

	public String getCreditcardDetailId() {
		return creditcardDetailId;
	}

	public void setCreditcardDetailId(String creditcardDetailId) {
		this.creditcardDetailId = creditcardDetailId;
	}

	public Menu getBillBankCodeMenu() {
		return billBankCodeMenu;
	}

	public void setBillBankCodeMenu(Menu billBankCodeMenu) {
		this.billBankCodeMenu = billBankCodeMenu;
	}

	public String getB100item() {
		return b100item;
	}

	public void setB100item(String b100item) {
		this.b100item = b100item;
	}

	public String getEditPeriod() {
		return editPeriod;
	}

	public void setEditPeriod(String editPeriod) {
		this.editPeriod = editPeriod;
	}

	public Menu getBillBankSingleCodeMenu() {
		return billBankSingleCodeMenu;
	}

	public void setBillBankSingleCodeMenu(Menu billBankSingleCodeMenu) {
		this.billBankSingleCodeMenu = billBankSingleCodeMenu;
	}

	public String getInvotype() {
		return invotype;
	}

	public void setInvotype(String invotype) {
		this.invotype = invotype;
	}

	public String getInvoTitle() {
		return invoTitle;
	}

	public void setInvoTitle(String invoTitle) {
		this.invoTitle = invoTitle;
	}

	public String getChkGiftCard() {
		return chkGiftCard;
	}

	public void setChkGiftCard(String chkGiftCard) {
		this.chkGiftCard = chkGiftCard;
	}

	public String getAllowSplit() {
		return allowSplit;
	}

	public void setAllowSplit(String allowSplit) {
		this.allowSplit = allowSplit;
	}

	public String getEditPeriodAmount() {
		return editPeriodAmount;
	}

	public Map<String, String> getProdVolumeMap() {
		return prodVolumeMap;
	}

	public void setEditPeriodAmount(String editPeriodAmount) {
		this.editPeriodAmount = editPeriodAmount;
	}

	public void setProdVolumeMap(Map<String, String> prodVolumeMap) {
		this.prodVolumeMap = prodVolumeMap;
	}

	public List<Orders> getJoinOrderList() {
		return joinOrderList;
	}

	public void setJoinOrderList(List<Orders> joinOrderList) {
		this.joinOrderList = joinOrderList;
	}

}